<template>

  <el-row :gutter="20">
    <el-col :xs="24" :sm="24" :lg="12">
      <el-card>
        <template #header>
          <div class="clearfix">
            <span>任务详情</span>
            <el-button
              style="float: right; margin-left: 10px"
              type="primary"
              size="small"
              @click="handleCreateChildTask();"
            >
              <Icon icon="ep:link" class="mr-5px"/>
              创建子协同
            </el-button>
            <el-button
              style="float: right;"
              type="primary"
              size="small"
              @click="handleAddExecutor();"
            >
              <Icon icon="ep:plus" class="mr-5px"/>
              添加执行人
            </el-button>
          </div>
        </template>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
          <el-form-item label="协作标题：" prop="taskName">
            <span v-if="!editable.taskName" @click="makeEditable('taskName')">{{
                form.taskName
              }}</span>
            <el-input v-else v-model="form.taskName" :ref="el => refs.taskName = el"
                      @blur="makeUneditable('taskName')"
            />
          </el-form-item>

<!--          <el-form-item label="状态：" prop="finishState">-->
<!--            &lt;!&ndash;            <dict-tag&ndash;&gt;-->
<!--            &lt;!&ndash;                v-show="!editable.finishState" @click="makeEditable('finishState')"&ndash;&gt;-->
<!--            &lt;!&ndash;                :type="DICT_TYPE.BUSINESS_FINISH_STATUS" :value="form.finishState"&ndash;&gt;-->
<!--            &lt;!&ndash;            />&ndash;&gt;-->
<!--            &lt;!&ndash;            <el-select&ndash;&gt;-->
<!--            &lt;!&ndash;                v-show="editable.finishState" v-model="form.finishState" :ref="el => refs.finishState = el"&ndash;&gt;-->
<!--            &lt;!&ndash;                placeholder="请选择完成状态"&ndash;&gt;-->
<!--            &lt;!&ndash;                @change="makeUneditable('finishState')" @blur="editable.finishState = false"&ndash;&gt;-->
<!--            &lt;!&ndash;            >&ndash;&gt;-->
<!--            &lt;!&ndash;              <el-option&ndash;&gt;-->
<!--            &lt;!&ndash;                  v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_FINISH_STATUS)"&ndash;&gt;-->
<!--            &lt;!&ndash;                  :key="dict.value"&ndash;&gt;-->
<!--            &lt;!&ndash;                  :label="dict.label"&ndash;&gt;-->
<!--            &lt;!&ndash;                  :value="dict.value"&ndash;&gt;-->
<!--            &lt;!&ndash;              />&ndash;&gt;-->
<!--            &lt;!&ndash;            </el-select>&ndash;&gt;-->
<!--            <el-radio-group-->
<!--              v-model="form.finishState"-->
<!--              :ref="el => refs.finishState = el"-->
<!--              @change="makeUneditable('finishState')"-->
<!--              @blur="editable.finishState = false"-->
<!--            >-->
<!--              <el-radio-->
<!--                v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_FINISH_STATUS)"-->
<!--                :key="dict.value"-->
<!--                :label="dict.value"-->
<!--                class="mr-4"-->
<!--                @click.prevent="handleFinishStateChangeBefore(dict.value)"-->

<!--              >-->
<!--                <el-tag type="dict.colorType">{{ dict.label }}</el-tag>-->
<!--              </el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->


          <el-form-item label="截止时间：" prop="deadline">
            <el-date-picker
              v-model="form.deadline"
              type="datetime"
              value-format="x"
              placeholder="请选择协作项截止时间"

              @change="makeUneditable('deadline')"
            />
          </el-form-item>

          <el-form-item label="优先级：" prop="priority">
            <span v-show="!editable.priority" @click="makeEditable('priority')">{{
                form.priority
              }}</span>
            <!--                <dict-tag-->
            <!--                    v-show="!editable.priority" @click="makeEditable('priority')"-->
            <!--                    :options="DICT_TYPE.BUSINESS_PRIORITY" :value="form.priority"-->
            <!--                />-->
            <el-select
              v-show="editable.priority" v-model="form.priority" :ref="el => refs.priority = el"
              placeholder="请选择完成状态"
              @change="makeUneditable('priority')" @blur="editable.priority = false"
            >
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_PRIORITY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="协作内容：" prop="content">
            <span v-if="!editable.content" @click="makeEditable('content', $event)"
                  v-html="form.content"></span>
            <div v-else>
              <editor v-model="form.content" :height="192"/>
              <div style="float: right;margin: 5px 0px">
                <el-button type="text" @click="editable.content = false">取消</el-button>
                <el-button type="primary" @click="makeUneditable('content')">保存</el-button>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="关联文件：" prop="taskFile">
            <upload-file v-model="form.taskFile" :is-show-tip="false"/>
            <el-button size="small" type="primary" @click="submitFile">保存</el-button>
          </el-form-item>

          <!--          <el-form-item label="协助人：" prop="assistUser">-->
          <!--            <cascader-user v-model="form.assistUser" placeholder="协助人" @change="makeUneditable('assistUser')"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="执行信息：" prop="execute">
            <el-table
              :data="flowList"
              style="width: 100%"
              show-overflow-tooltip
              size="small"
            >
              <el-table-column prop="title" label="标题" width="80"/>
              <el-table-column prop="userId_dictText" label="执行人" width="60"/>
              <el-table-column prop="startTime" label="开始时间" width="150">
                <template #default="scope">
                  {{ formatDate(scope.row.startTime) }}
                </template>
              </el-table-column>

              <el-table-column prop="state" label="完成状态" width="80">
                <template #default="scope">
                  <el-tag v-if="scope.row.state === 'going'" type="warning">进行中</el-tag>
                  <el-tag v-if="scope.row.state === 'finish'" type="success">已完成</el-tag>
                </template>
              </el-table-column>


              <el-table-column prop="endTime" label="完成时间" width="150">
                <template #default="scope">
                  {{ formatDate(scope.row.endTime) }}
                </template>
              </el-table-column>

              <el-table-column prop="deadline" label="截止时间" width="150">
                <template #default="scope">
                  {{ formatDate(scope.row.deadline) }}
                </template>
              </el-table-column>


              <el-table-column prop="creator_dictText" label="发起人" width="60"/>

              <el-table-column label="操作" width="60" fixed="right">
                <template #default="scope">
                  <el-button type="text" v-show="scope.row.state=='going'"
                             @click="handleFlowFinish(scope.row)">完成
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <div v-if="childTaskList&&childTaskList.length>0">
          <el-divider content-position="left">关联子协同：</el-divider>
          <el-table
            :data="childTaskList"
            style="width: 100%"
            show-overflow-tooltip
          >

<!--            <el-table-column prop="finishState" label="完成状态" width="100">-->
<!--              <template #default="scope">-->
<!--                <dict-tag :type="DICT_TYPE.BUSINESS_FINISH_STATUS" :value="scope.row.finishState"/>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column prop="taskName" label="协作标题" width="150"/>
            <el-table-column prop="executeUser_dictText" label="执行人" width="80"/>
            <el-table-column prop="executeUser" label="开始时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="executeUser" label="截止时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.deadline) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="60" fixed="right">
              <template #default="scope">
                <el-button type="text"
                           @click="handleTask(scope.row)">查看
                </el-button>
              </template>
            </el-table-column>


          </el-table>

        </div>
      </el-card>
    </el-col>

    <el-col :xs="24" :sm="24" :lg="12">
      <el-card class="box-card" style="min-height: 800px">
        <template #header>
          <div class="clearfix">
            <span>所有动态</span>
            <el-button
              style="float: right; padding: 3px 0" type="text" icon="el-icon-refresh"
              @click="getTaskDetails(taskId)"
            >刷新
            </el-button>
          </div>
        </template>
        <div class="remark-content">
          <div v-for="log in logList" :key="log.id">
            <div class="remark-item">
              <!-- 操作 -->
              <div v-if="log.type === '操作'" class="remark-handle">
                <span style="float: right">{{ formatDate(log.createTime) }}</span>
                <span
                  class="remark-item-content-text" v-html="log.content" style="width: 100%"
                  @click="openImg($event)"
                ></span>
              </div>

              <!-- 备注 -->
              <div v-else class="remark-remark">
                <div class="topRemark">
                  <div>
                    <img
                      class="user-avatar"
                      :src="log.avatar ? log.avatar : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                    />
                    <span style="font-size: 15px;line-height: 30px; padding-left: 5px;"
                    >{{ log.creator_dictText }}</span>
                  </div>
                  <div style="float: right;">
                    <span style="font-size: 15px;line-height: 30px">{{
                        formatDate(log.createTime)
                      }}</span>
                  </div>
                </div>

                <div class="bottomRemark"></div>

                <div class="remark-item-content">
                      <span
                        class="remark-item-content-text" v-html="log.content" style="width: 100%"
                        @click="openImg($event)"
                      ></span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-divider/>
        <el-row :gutter="5">
          <el-col :span="22">
            <div class="remark-bottom">
              <editor v-model="content" :height="150"/>
            </div>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="handleAddRemark">评论</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>

  <el-dialog v-model="flowVisible" title="添加执行人" width="500">
    <el-form :model="flowForm" ref="flowFormRef" :rules="flowRules">
      <el-form-item label="协作标题" prop="taskName">
        <el-input class="!w-240px" v-model="flowForm.taskName"/>
      </el-form-item>
      <el-form-item label="执行人" prop="executeUser">
        <cascader-user class="!w-240px" v-model="flowForm.executeUser"/>
      </el-form-item>
      <el-form-item label="截止时间" prop="deadline">
        <el-date-picker
          v-model="flowForm.deadline"
          type="datetime"
          value-format="x"
          placeholder="请选择协作项截止时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="flowVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitAddExecutor">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <WorkTaskForm ref="workTaskFormRef" @success="initData"/>
</template>

<script setup>

import {useUserStore} from "@/store/modules/user";
import {ProjectTaskLogApi} from '@/api/business/synergy/project/taskLog'
import {DICT_TYPE, getDictOptions} from '@/utils/dict'
import {formatDate} from "../../../../../utils/formatTime";
import {useRoute} from "vue-router";
import {WorkTaskApi} from "@/api/business/synergy/work/task";
import {WorkflowInfoApi} from "@/api/business/general/workflow/flow";
import WorkTaskForm from "@/views/business/synergy/work/components/workTaskForm.vue";
import router from "@/router";

const message = useMessage() // 消息弹窗
const userStore = useUserStore()


// 响应式变量
const visible = ref(false)
const flowVisible = ref(false)
const title = ref('')
const content = ref('')
let form = ref({})
const logList = ref([])
const flowList = ref([])
const formRef = ref(null)
const tempData = ref('')

const flowForm = ref({})
const flowFormRef = ref(null)

const refs = reactive({})
const childTaskList = ref([])
const workTaskFormRef = ref()


// 编辑状态管理
const editable = reactive({
  taskName: false,
  finishState: false,
  executeState: false,
  executeUser: false,
  deadline: false,
  priority: false,
  label: false,
  content: false,
  taskFile: false,
  assistUser: false
})

// 验证规则
const rules = ref({})

const flowRules = ref({
  executeUser: [
    {
      required: true,
      message: '请选择执行人',
      trigger: 'blur'
    }
  ],
  taskName: [
    {
      required: true,
      message: '请输入协作标题',
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 打开图片预览
const openImg = (e) => {
  if (e.target.nodeName === 'IMG') {
    if (e.target.src.startsWith('data:image')) {
      // 如果是 base64 格式的图片，创建临时链接并在新标签页中显示
      let byteCharacters = atob(e.target.src.split(',')[1])
      let byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      let byteArray = new Uint8Array(byteNumbers)
      let blob = new Blob([byteArray], {type: 'image/png'})
      let imageUrl = URL.createObjectURL(blob)
      window.open(imageUrl, '_blank')
    } else {
      // 如果不是 base64 格式的图片，直接在新标签页中显示
      window.open(e.target.src, '_blank')
    }
  }
}


const {params} = useRoute() // 查询参数
const taskId = params.id


onMounted(() => {
  initData()
})


const initData = async () => {
  await getTaskDetails(taskId)
}

// 获取任务详情
const getTaskDetails = async (taskId) => {
  form.value = await WorkTaskApi.getWorkTask(taskId)
  let flowQueryForm = {
    taskId: taskId,
    module: 'synergy'
  }
  let flowData = await WorkflowInfoApi.getWorkflowInfoPage(flowQueryForm)
  flowList.value = flowData.list
  let logData = await ProjectTaskLogApi.getProjectTaskLogPage({taskId})
  logList.value = logData.list


  let childData = await WorkTaskApi.getWorkTaskPage({parentId: taskId})
  childTaskList.value = childData.list


  await nextTick(() => {
    const chatContainer = document.querySelector('.remark-content')
    if (chatContainer && chatContainer.scrollHeight) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  })
}


// 改变前的处理方法
const handleFinishStateChangeBefore = (newValue) => {
  const oldValue = form.value.finishState;
  // 值未变化则不处理
  if (oldValue === newValue) return;
  if (userStore.user.id.toString() !== '1') {
    if (form.value.creator !== userStore.user.id.toString()) {
      message.error('您不是创建者，不能修改状态')
      return
    }
  }


  if (oldValue === '已完成') {
    message.warning('任务已完成,操作失败!')
    return;
  }

  form.value.finishState = newValue;
  updateTaskHandler('finishState')
};

// 切换到编辑状态
const makeEditable = (field, $event) => {
  tempData.value = form.value[field]
  if (field === 'content' && $event) {
    openImg($event)
  }

  editable[field] = true

  nextTick(() => {
    refs[field]?.focus()  // ?. 防止字段不存在时报错
  })
}

// 切换到非编辑状态
const makeUneditable = (field) => {
  editable[field] = false
  if (!form.value[field]) return
  if (tempData.value === form.value[field]) return
  updateTaskHandler(field)

}

// 提交文件
const submitFile = () => {
  if (form.value.taskFile) {
    updateTaskHandler('taskFile')
  }
}

// 更新任务
const updateTaskHandler = async (column) => {
  form.value.params = {column: column}
  if (column === 'taskFile') {
    if (Array.isArray(form.value.taskFile)) {
      form.value.taskFile = form.value.taskFile.join(',')
    }
  }
  await WorkTaskApi.updateWorkTask(form.value)
  emit('success');
  message.success("操作成功")
  await getTaskDetails(form.value.id)
}

// 添加评论
const handleAddRemark = async () => {
  const logForm = {
    taskId: form.value.id,
    content: content.value,
  }
  await ProjectTaskLogApi.createProjectTaskLog(logForm)
  content.value = ''
  await getTaskDetails(form.value.id)
}

//完成流程
const handleFlowFinish = async (row) => {
  if (row.creator == userStore.user.id.toString() || userStore.user.id.toString() == '1' || userStore.user.id.toString() == row.userId) {
    ElMessageBox.prompt('请填写完成备注', '请确认是否完成任务？', {
      confirmButtonText: '完成',
      cancelButtonText: '取消',
    })
      .then(({value}) => {
        let finishFlowForm = {
          id: row.id,
          remark: value
        }
        WorkTaskApi.finishExecuteTask(finishFlowForm).then(res => {
          getTaskDetails(taskId)
          message.success('操作成功')
        })
      })
  } else {
    message.error('操作失败！暂无权限')
  }
}

const handleCreateChildTask = async () => {
  workTaskFormRef.value.open(taskId)
}

const handleTask = (task) => {
  let id = task.id
  router.push({name: 'SynergyWorkTask', params: {id}})
}

const handleAddExecutor = () => {
  flowForm.value = {}
  flowForm.value.id = taskId
  flowForm.value.taskName = form.value.taskName
  if (form.value.deadline) {
    flowForm.value.deadline = form.value.deadline
  }
  flowVisible.value = true
}

const submitAddExecutor = async () => {
  await flowFormRef.value.validate()
  await WorkTaskApi.addExecuteTask(flowForm.value)
  await getTaskDetails(taskId)
  flowVisible.value = false
  message.success('操作成功')


}
</script>


<style scoped>
/* 动态列表容器优化 */
:deep(.remark-content) {
  overflow: auto;
  min-height: 400px !important;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
  box-sizing: border-box;

  /* 滚动条美化 */

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #d1d5db;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: #9ca3af;
  }
}

/* 单个动态项容器 - 统一基础样式 */
:deep(.remark-item) {
  margin-bottom: 2px; /* 减小项之间的间距 */
  padding: 2px 0; /* 增加内部上下边距 */
  transition: all 0.2s ease;

  &:last-child {
    margin-bottom: 0;
  }

  &:hover {
    transform: translateY(-1px);
  }
}

/* 操作类型动态样式（系统日志）- 去除容器感 */
:deep(.remark-handle) {
  color: #6b7280;
  padding: 5px 0; /* 仅保留上下内边距 */
  font-size: 13px;
  line-height: 1.5;

  /* 系统提示时间样式 */

  span[style*="float: right"] {
    color: #9ca3af;
    margin-left: 8px;
    font-size: 12px;
  }

  .remark-item-content-text {
    display: block;
    padding: 2px 0;
  }
}

/* 用户备注动态样式 - 减小间距 */
:deep(.remark-remark) {
  position: relative;
  padding: 4px 10px; /* 减小内边距 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);

  &::before {
    content: '';
    position: absolute;
    left: 5px;
    top: 16px;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: #409eff;
  }

  /* 头像和时间所在的顶部容器 */

  .topRemark {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 5px; /* 减小底部间距 */
    margin-bottom: 5px; /* 减小与内容的间距 */
    border-bottom: 1px dashed #f0f0f0;
    height: 25px; /* 略微减小高度 */
  }

  /* 头像和用户名容器 */

  .topRemark div:first-child {
    display: flex;
    align-items: center;
    height: 100%;
  }

  /* 头像样式 */

  .user-avatar {
    width: 30px !important; /* 适当减小头像 */
    height: 30px !important;
    border-radius: 50%;
    margin-right: 8px;
    margin-top: 8px;
    border: 1px solid #eee;
    flex-shrink: 0;
    transition: transform 0.2s ease;

    &:hover {
      transform: scale(1.05);
    }
  }

  /* 用户名 */

  .topRemark span:first-of-type {
    font-weight: 500;
    color: #333;
    line-height: 28px; /* 与头像高度匹配 */
  }

  /* 时间容器 */

  .topRemark div:last-child {
    display: flex;
    align-items: center;
    height: 100%;
  }

  /* 时间文本 */

  .topRemark span:last-of-type {
    font-size: 12px;
    color: #999;
    line-height: 28px; /* 与头像高度匹配 */
    white-space: nowrap;
  }

  /* 评论内容区域 */

  .remark-item-content {
    padding-left: 14px; /* 与左侧标识对齐 */

    .remark-item-content-text {
      line-height: 1.5; /* 减小行高 */
      color: #444;
      word-break: break-all;
      font-size: 14px;
    }
  }
}

/* 动态内容中的图片优化 */
:deep(.remark-item-content-text img) {
  max-width: 30%;
  height: auto;
  border-radius: 4px;
  margin: 6px 0; /* 减小图片上下间距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: zoom-in;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }
}

/* 底部评论区与动态列表分隔 */
:deep(.el-divider) {
  margin: 12px 0; /* 减小分隔线上下间距 */
  background-color: #e5e7eb;
}

/* 评论输入区样式优化 */
.remark-bottom {
  max-height: 300px; /* 减小最大高度 */
  overflow-y: auto;
  padding: 6px; /* 减小内边距 */
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  transition: border-color 0.2s ease;

  &:focus-within {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
  }
}

/* 评论按钮优化 */
:deep(.el-col:nth-child(2) .el-button) {
  margin-top: 6px; /* 减小按钮顶部间距 */
  transition: all 0.2s ease;

  &:hover {
    transform: translateY(-1px);
  }
}
</style>




